<?php


namespace app\admin\controller;


use app\common\model\Users;
use app\lib\exception\admin\ErrorsException;
use app\admin\authentication\Jwt;
//model 模型
use app\admin\model\{
    Admin as AdminModel,
    Users as UsersModel
 };
//facade 门面
use think\facade\{App, Cache, Config, Db, Request};

class Admin
{

    public function getIndex(Request $request){
        //获取token
        $headerToken = $request::header('x-token');
        $userInfo = (new Jwt())->checkJwtToken($headerToken);
        $getMenus = $this->getMenus($headerToken);
        //当前MSQl版本
        $version = Db::query('SELECT VERSION() AS ver');
        //获取系统信息
        $configs = [
            'url' => $_SERVER['HTTP_HOST'],
            'document_root' => $_SERVER['DOCUMENT_ROOT'],
            'server_os' => PHP_OS,
            'server_port' => $_SERVER['SERVER_PORT'],
            'server_ip' => isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '',
            'server_soft' => $_SERVER['SERVER_SOFTWARE'],
            'php_version' => PHP_VERSION,
            'mysql_version' => $version[0]['ver'],
            'max_upload_size' => ini_get('upload_max_filesize'),
            'version' => App::version(),
            'admin_version' => Config::get('app.admin_version'),
        ];

        //查找一周内注册用户信息
        $user = UsersModel::where('create_time', '>', time() - 60 * 60 * 24 * 7)->count();

        $data = array(
            'code' => 200,
            'user' => $user,
            'configs' =>$configs,
            'menus' =>$getMenus,
            'userInfo' =>$userInfo,
            'msg' => '返回成功'
        );

        return json($data);
    }

    /**
     * 获取左侧菜单栏
     * @param Request $request
     * @return array|void
     * @throws \app\lib\exception\admin\AuthenticationException
     */
    public function getMenus($headerToken){
        //获取token
        //$headerToken = $request::header('x-token');
        //通过jwt拿到数据
        $userInfo = (new Jwt())->checkJwtToken($headerToken);
        //查看前端的token和缓存的token是否一致
        $checkToken = Cache::get('token'.$userInfo['id']);
        if(!($headerToken == $checkToken)){
            throw new ErrorsException([
                'code' => 301,
                'msg' => 'token 不存在或已过期',
                'error_code' => 30001,
            ]);
        }
        //获取侧边列表
        $getMenus = AdminModel::getMenus($userInfo);
        return $getMenus;
    }
}